package com.example.asus.databasedemo1;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by asus1 on 2017/11/2.
 */

public class ContactCAO {
    MyDbHelper myDbHelper = null;

    ContactCAO(Context context) {
        myDbHelper = new MyDbHelper(context);
    }

    public void insertData(String cardName, String cost) {
        SQLiteDatabase db = myDbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(MyDbHelper._CARDNAME, cardName);
        values.put(MyDbHelper._COST, cost);
        db.insert(MyDbHelper.TABLE_NAME, null, values);
    }

    public void deleteData(String element, String elementContent) {
        SQLiteDatabase db = myDbHelper.getWritableDatabase();
        db.delete(MyDbHelper.TABLE_NAME, element + "=?", new String[]{elementContent});
    }

    public void updateData(String cardName, String newCost) {
        SQLiteDatabase db = myDbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(MyDbHelper._CARDNAME, cardName);
        values.put(MyDbHelper._COST, newCost);
        db.update(MyDbHelper.TABLE_NAME, values, MyDbHelper._CARDNAME + "=?", new String[]{cardName});
    }

    public Cursor queryData(String element, String elementContent) {
        SQLiteDatabase db = myDbHelper.getReadableDatabase();
        if (element == null) {
            return db.query(MyDbHelper.TABLE_NAME, null,
                    null, null, null, null, null);
        }
        return db.query(MyDbHelper.TABLE_NAME, new String[]{MyDbHelper._ID, MyDbHelper._CARDNAME, MyDbHelper._COST},
                element + "=?", new String[]{elementContent}, null, null, null);
    }
}
